<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 05/09/2017
 * Time: 22:32
 */
namespace frontend\controllers;

use common\models\ar\MoneyChangeDirection;
use common\models\ar\MoneyRecharge;
use common\models\ar\SysConfig;
use common\models\MoneyDao;
use common\models\OrderDao;
use common\models\Pay;
use common\models\RechargeDaos;
use common\models\ar\ExchangeRate;
use common\models\ar\BankMs;
class MoneysController extends FrontendController
{
    /**
     * 资金变更记录
     */
    public function actionHistory()
    {
        $uid = \Yii::$app->user->identity->uid;
        $req = \Yii::$app->request;
        $isRender = $req->get('isRender', 1);
        $direction = $req->get('direction', -1);//变更类型
        //资金类型
        $tmp = MoneyChangeDirection::find()->where(['level_5_show_flag' => 1])->asArray()->all();
        $directions = [];
        foreach ($tmp as $v) {
            $directions[$v['id']] = $v;
        }

        if ($direction != -1) {
            $direction = [$direction];
        }

        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;

        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;

        $data = MoneyDao::history($direction, -1, -1, $uid, $from, $to, $pageNo, $pageSize);
        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = MoneyDao::history($direction, -1, -1, $uid, $from, $to, $pageNo, $pageSize);
            }
        }

        $data['from'] = $from;
        $data['to'] = $to - 1;
        $data['directions'] = $directions;
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = ceil($data['total'] / $pageSize);

        if ($isRender == 1) {
            return $this->renderPartial('history', $data);
        } else {
            exit(json_encode($data));
        }
    }

    /**
     * 充值
     *
     * @return string
     */
    public function actionRecharge()
    {
        $req = \Yii::$app->request;
        $db = \Yii::$app->db;
        $sql="SELECT * FROM `bank_ms`";
        $banks=$db->createCommand($sql)->queryAll();
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        //获取汇率值
        $RMB=ExchangeRate::findOne(['currency'=>'RMB']);
        $RMB=$RMB['exchange_rate'];
        //充值费率
        $tmp = SysConfig::find()->where(['key' => 'recharge_rate'])->asArray()->one();
        $rechargeRemark = "充值费率：";
        if (!$tmp) {
            $rechargeRemark .= "8";
        } else {
            $rechargeRemark .= $tmp['value'] * $tmp['percent'];
        }
        $rechargeRemark .= "‰，此费用由 \"第三方中国银联在线\" 收取";
        return $this->renderPartial('recharge', [
            'from' => $from,
            'to' => $to,
            'rechargeRemark' => $rechargeRemark,
            'RMB'=>$RMB,
            'banks'=>$banks
        ]);
    }

    /**
     * 本次充值记录
     */
    public function actionRechargeSubmit()
    {
        $uid = \Yii::$app->user->identity->id;
        $req = \Yii::$app->request;
        $money = $req->post('money', 0);
        $banks=$req->post("bank",0);
        if (!is_numeric($money) || !$money) {
            $code = 1004;
            $msg = "请输入正确的金额";
            exit(json_encode(['code' => $code, 'msg' => $msg]));
        }
        // if ($money < 100) {
        //     $code = 1005;
        //     $msg = "入金金额不能小于100元";
        //     exit(json_encode(['code' => $code, 'msg' => $msg]));
        // }
        //$rechargeSN = uniqid('P');
        $rechargeSN ="WY" . date("ymd_His") . rand(10, 99);
        $time = time();
//        $payType=$req->post("payType");
        $obj = new MoneyRecharge();
        $attr = [
            'recharge_sn' => $rechargeSN,
            'userID' => $uid,
            'direction' => 9, // 充值：入金
            'type' => 2,
            'money' => $money,
            'pay_start_time' => $time,
            'bank_code' => $banks,//没有实际意义，到第三方支付页面需要重新选择
            'status' => 1,
            'data_request' => json_encode($_POST),
        ];
        $obj->attributes = $attr;
        if (!$obj->save()) {
            $code = 0;
            $msg = "请求失败";
        } else {
            $code = 1;
            $msg = "ok";
        }
        exit(json_encode(['code' => $code, 'msg' => $msg, 'rechargeSN' => $rechargeSN]));
    }


    /**
     * 跳转到第三方支付的表单
     */
    public function actionRechargePayForm()
    {
        // return $this->render('index');
       //        echo "开发中";
      //        exit();

        $uid = \Yii::$app->user->identity->id;
        $ip = $_SERVER['REMOTE_ADDR'];
        date_default_timezone_set('Asia/Shanghai');
        $rechargeSN = \Yii::$app->request->get('rechargeSN', '');
        $sql = "SELECT
                    a.*
                FROM
                    `money_recharge` a
                WHERE  a.`recharge_sn` = :recharge_sn 
                AND a.`userID` = $uid
        ";
        $res = \Yii::$app->db->createCommand($sql, [':recharge_sn' => $rechargeSN])->queryOne();
        $time=date("YmdHis");
        if (!$res) {
            exit("request error!");
        }
        $payParams = \Yii::$app->params['pay'];
        $data = array();
        $data["appid"]="1994001";
        $data["tf_timestamp"]=$time;
        $data["sign_type"] = "MD5";
        $data["terminal"] = "PC";
        $data["service_id"] = "tf56pay.gateway.bankPay";
        $data["fronturl"] = $payParams['fronturl'];
        $data["backurl"] = $payParams['backurl'];
        $data["subject"] = "充值";
        $data["businesstype"] = "互联网金融";
        $data["kind"] ="其他互联网金融";
        $data["businessnumber"]=$res['recharge_sn'];
        $data["transactionamount"]=$res["money"];
        $data["toaccountnumber"]= $payParams['toaccountnumber'];
        $data["bankcode"]=$res['bank_code'];
        $data["bankaccounttype"]="储蓄卡";
        $data["accountproperty"]="对私";
        $data["clientip"]=$ip;
        $data["merchtonline"]="0";
        $pay = new Pay();
//        ksort($data);
        //签名，设为sign字段值。
        $data['tf_sign'] = $pay->SignArray($data,$payParams['key']);//签名
        // var_dump($data);
        // exit();
        $data_ht= http_build_query($data);
        $postUrl=$payParams['api']['real_name_auth'];
        $ch=curl_init();//初始化
        curl_setopt($ch, CURLOPT_URL,$postUrl);//指定网页
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type'=>'x-www-form-urlencoded;charset=UTF-8'));
        curl_setopt($ch, CURLOPT_HEADER, 1);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_ht);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
        $datas = curl_exec($ch);//运行curl
//         $errno=curl_errno($ch);
        curl_close($ch);
        $datas=substr($datas,strpos($datas,'{"biz_code'));
        $datas_array=json_decode($datas,true);
        $data_code=$datas_array['biz_code'];
       if($datas_array['biz_code']=="GPBIZ_00"){
            if ($datas_array['biz_code']!="GPBIZ_021002"){
            if ($datas_array['code']=="GP_00"){
                $datas=json_decode($datas_array['data'],true);
                echo base64_decode(urldecode($datas['htmldata']));
//            return $this->renderPartial('recharge-pay-form', ['url'=> base64_decode($datas['htmldata'])]);
            }else{
                echo "<script>alert('订单支付失败，请核实订单信息！');</script>";
            }
        }else{
            echo "<script>alert('暂时不支持此银行支付！');</script>";
        }
        }else{
            echo "<script>alert('未知错误，错误码信息：".$data_code."');</script>";
        }
//        $bufSignSrc = $pay->ToUrlParams($data);
//        return $this->renderPartial('recharge-pay-form', ['url' => $payParams['api']['real_name_auth'], 'post' => $data]);
    }

    /**
     * 第三方支付跳回后需要显示给客户
     */
    public function actionRechargeReturn()
    {
         $req=file_get_contents("php://input");
         $file=fopen("1.txt","w");
         fwrite($file,$req);
         fclose($file);
         exit();
        return $this->redirect("/moneys/recharge");
    }

    /**
     * 充值历史
     */
    public function actionRechargeHistory()
    {
        $uid = \Yii::$app->user->identity->userID;
        $req = \Yii::$app->request;
        $status = $req->get('status', -1);//充值状态
        $from = $req->get('from', date('Ymd', time() - 7 * 24 * 3600));
        $to = $req->get('to', date('Ymd'));
        $from = strtotime($from);
        $to = strtotime($to) + 24 * 3600;
        $pageNo = $req->get('pageNo', 1);
        $pageSize = 15;
        $data = RechargeDaos::history($status, $uid, $from, $to, $pageNo, $pageSize);
        $pageTotal = ceil($data['total'] / $pageSize);
        if ($pageTotal == 0) {
            $pageNo = 1;
        } else {
            if ($pageNo > $pageTotal) {
                $pageNo = $pageTotal;
                $data = RechargeDaos::history($status, -1, -1, $uid, $from, $to, $pageNo, $pageSize);
            }
        }
        $data['pageNo'] = $pageNo;
        $data['pageTotal'] = $pageTotal;
        exit(json_encode($data));
    }
}
